<?php

namespace app\admin\controller\sta;

use app\admin\library\Auth;
use app\admin\model\Depot;
use app\admin\model\Mcategory;
use app\admin\model\Material as Mmaterial;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Collection;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 物料收发存汇总管理
 *  todo -- 成本报表02-物料收发存汇总表
 * @icon fa fa-circle-o
 */
class Material extends Backend
{

    /**
     * Material模型对象
     * @var \app\admin\model\sta\Material
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sta\Material;
        #$this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statusList", [] );
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //  物料基本信息
        //  注:  此控制器为对应汇总表(sta_material) , 但主体model取 物料基本信息表: (m_info)
        //  TODO:  功能完成后, 需要改为: 查询完成上月的数据后,记录存到表sta_material, 并锁定数据不可修改
        //  TODO:  查询条件:  月份,当月可修改;  (可能还会按厂区拆分)
        $infoModel = new \app\admin\model\m\Info;
        //  计算月份      *
        //   todo   需要改成可选月份
        //   查询本月数据是随动的,单条记录不可修改.  查询上月数据是已存到表 sta_material 的, 查询当月是即时的
        //   todo    $newdate  需要做成用户选择
        $newdate = date("Y-m-01");          // 月初       todo
        $newdate_31 = date("Y-m-d", strtotime("+1 month", strtotime($newdate) )  );    // 月底
        // 汇总月份
        $this->view->assign("mark", date("ym", strtotime($newdate) )."月" );

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        // 关联表查询
        $depotList = Depot::getList();
        $materialList = Mmaterial::getList();
        $mcategoryList = Mcategory::getList();


        //  数据行:  物料信息,id 即是  m_info.id
        $list = $infoModel->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach($list as &$val){
            $val['depot_id'] = $depotList[$val['depot_id']];
            $val['mmaterial_id'] = $materialList[$val['mmaterial_id']];
            $val['mcategory_id'] = $mcategoryList[$val['mcategory_id']];
            // 计算月份
            $val['createtime'] = $newdate;           //  todo
        }

        //  上月期末库存   @wtt
        $lastData = $this->getLastStock($newdate);

//print_r($lastData); die;

        // TODO:  如果计算合计,  那么要按当前筛选条件, 进行`不分页` 计算

        // TODO:  采集对应数据
        foreach($list as &$val){
            $bill_buy = Db::name("m_stockbill")
                ->field("sum(nums) as bill_num, sum(total_price) as bill_total ")
                ->where(['info_id'=> $val['id'], 'type'=>'采购', 'status'=>'已通过' ])
                ->where('newdate' , 'between', [ $newdate, $newdate_31 ] )
                ->find();

            $bill_allot = Db::name("m_stockbill")
                ->field("sum(nums) as bill_num, sum(total_price) as bill_total ")
                ->where(['info_id'=> $val['id'], 'type'=>'调拨', 'status'=>'已通过' ])
                ->where('newdate' , 'between', [ $newdate, $newdate_31 ] )
                ->find();
            $bill_sale = Db::name("m_stockbill")
                ->field("sum(nums) as bill_num, sum(total_price) as bill_total ")
                ->where(['info_id'=> $val['id'], 'type'=>'销售', 'status'=>'已通过' ])
                ->where('newdate' , 'between', [ $newdate, $newdate_31 ] )
                ->find();

            $lingyong = Db::name("m_apply")
                ->field("sum(num) as bill_num, sum(price) as bill_total ")
                ->where(['info_id'=> $val['id'], 'status'=>'已通过' ])
                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
                ->find();
            $lingyong_else = Db::name("m_applyes")
                ->field("sum(num) as bill_num, sum(price) as bill_total ")
                ->where(['info_id'=> $val['id'], 'status'=>'已通过' ])
                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
                ->find();

            //echo Db::getLastSql();die;
            // 物料单价,  @wtt   当月录入的价格
            // TODO  次月价格变更后 (加权平均...) ,   重新录入一组数据,
            //  (每月显示一组库存数据, 不叠加上月的数据.  每月结算后,创建下月的一组数据. )

            $lingyong_unit = Db::name("m_stock")
                ->field("info_id, price")
                ->where(['status'=> '已通过' ])
                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
                ->select();
            $lingyong_unit = array_column($lingyong_unit, "price", "info_id");


            //print_r($lingyong_unit);die;
//echo Db::getLastSql();die;
            //  TODO  重要  这里暂时没计算加权平均
            $val['a'] = $lastData[$val['id']]['o'] ;      //期初数量 总     TODO  期初金额, 可以在期初时先在表  sta_material  创建空记录! 录入金额或者由上次记录结账转换
            $val['b'] = $lastData[$val['id']]['q'] ;      //期初金额 总
            $val['c'] = $bill_buy['bill_num'] ;      //采购单数量
            $val['d'] = $bill_buy['bill_total'] ;      //采购单金额
            $val['e'] = $bill_allot['bill_num'] ;      //调拨单数量
            $val['f'] = $bill_allot['bill_total'] ;      //调拨单金额
            $val['g'] = $lingyong_else['bill_num'];      //其他领用数量
            $val['h'] = $lingyong_else['bill_total'];      //其他领用金额
            $val['i'] = 0;      //生产入库单数量
            $val['j'] = 0;      //生产入库单金额
            $val['k'] = $lingyong['bill_num'];      //领用单数量
            $val['l'] = isset($lingyong_unit[ $val['id'] ])? number_format($lingyong_unit[ $val['id'] ]*$lingyong['bill_num'], 2, '.', '') : 0  ;      //领用单金额
            // var_dump ( $val['l'] ); die;
            $val['m'] = $bill_sale['bill_num'];      //销售单数量     todo 暂无销售物料单, 增加销售物料单后, 查销售单即可    salematerial 表待增加+
            $val['n'] = $bill_sale['bill_total'];      //销售单金额
            $val['o'] = $val['a'] + $val['c'] + $val['e'] - $val['m'] - $val['g'] - $val['k'];      //期末库存数量=  期初+采购+调拨入-销售-领用
            $val['p'] = isset($lingyong_unit[ $val['id'] ]) ? $lingyong_unit[ $val['id'] ] : 0 ;      //期末库存单价    TODO  暂取期初单价, 可能期末就要加权平均
            $val['q'] = number_format( $val['b'] + $val['d'] + $val['f'] - $val['l'] - $val['h'] - $val['n'], 2, '.', '' ) ;      //期末库存金额
        }

         // 计算 合计(暂定以下几项):    采购单金额, 调拨单金额,  领用单金额,   期末库存金额
         $sumArr[0] = ['depot_id'=>'合计', 'c' => 0.00, 'd'=> 0.00,'f'=> 0.00, 'l'=>0.00, 'q'=>0.00 , 'g'=>0.00, 'h'=>0.00 ];
         foreach($list as $k => $val) {
             $sumArr[0]['c'] += $val['c'];
             $sumArr[0]['d'] += $val['d'];
             $sumArr[0]['f'] += $val['f'];
             $sumArr[0]['l'] += $val['l'];
             $sumArr[0]['q'] += $val['q'];
             $sumArr[0]['g'] += $val['g'];
             $sumArr[0]['h'] += $val['h'];
         }

        // 数据+合计合并到一起
        $mer = array_merge( $list->items() , $sumArr );



        #$result = ['total' => $list->total(), 'rows' => $list->items()];
        $result = ['total' => $list->total(), 'rows' => $mer ];
        return json($result);
    }


    //  获取上月月末库存
    public function getLastStock( $newdate ){
        // 上次结算的数据.     TODO  这里获取方法写的不准确,   do: 获取当前月份的前一次数据

        $date = date("Y-m", strtotime("-1 month", strtotime($newdate) )  );    // 月底
//print_r($date); die;
        $lastList = Db::name("sta_material")
            ->where("DATE_FORMAT(createtime,'%Y-%m')='{$date}' ")
            ->select();

        $lastArr = $lastList ;
        $lastData = array_column( $lastArr , null, 'info_id' );

        return $lastData ;
    }


    /**
     * 回收站
     *
     * @return string|Json
     * @throws \think\Exception
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->onlyTrashed()
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 真实删除
     *
     * @param $ids
     * @return void
     */
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $this->model->where($pk, 'in', $ids);
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 还原
     *
     * @param $ids
     * @return void
     */
    public function restore($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    protected function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }


}
